// Arduino门禁控制器代码
#include <Arduino.h>

// 定义引脚
const int RELAY_PIN = 2;
const int BUZZER_PIN = 3;
const int GREEN_LED_PIN = 4;
const int RED_LED_PIN = 5;

// 门禁状态
bool doorLocked = true;

void setup() {
  Serial.begin(9600);
  
  // 设置引脚模式
  pinMode(RELAY_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  pinMode(GREEN_LED_PIN, OUTPUT);
  pinMode(RED_LED_PIN, OUTPUT);
  
  // 初始化状态
  digitalWrite(RELAY_PIN, HIGH); // 默认锁门
  digitalWrite(RED_LED_PIN, HIGH); // 红灯亮表示锁定
  digitalWrite(GREEN_LED_PIN, LOW);
  digitalWrite(BUZZER_PIN, LOW);
}

// 开门操作
void unlockDoor() {
  digitalWrite(RELAY_PIN, LOW); // 开锁
  digitalWrite(RED_LED_PIN, LOW);
  digitalWrite(GREEN_LED_PIN, HIGH); // 绿灯亮表示解锁
  
  // 蜂鸣器提示
  digitalWrite(BUZZER_PIN, HIGH);
  delay(200);
  digitalWrite(BUZZER_PIN, LOW);
  
  doorLocked = false;
  Serial.println("DOOR_UNLOCKED");
  
  // 10秒后自动锁门
  delay(10000);
  lockDoor();
}

// 锁门操作
void lockDoor() {
  digitalWrite(RELAY_PIN, HIGH); // 锁门
  digitalWrite(GREEN_LED_PIN, LOW);
  digitalWrite(RED_LED_PIN, HIGH); // 红灯亮表示锁定
  
  doorLocked = true;
  Serial.println("DOOR_LOCKED");
}

void loop() {
  // 检查串口指令
  if (Serial.available() > 0) {
    String command = Serial.readStringUntil('\n');
    command.trim();
    
    if (command == "UNLOCK") {
      if (doorLocked) {
        unlockDoor();
      }
    } else if (command == "LOCK") {
      if (!doorLocked) {
        lockDoor();
      }
    } else if (command == "STATUS") {
      // 发送当前状态
      Serial.println(doorLocked ? "LOCKED" : "UNLOCKED");
    }
  }
  
  delay(100);
}